import { useEffect, useRef } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { Link } from 'react-router-dom'
import {
  Card,
  Breadcrumb,
  Form,
  Radio,
  Button,
  DatePicker,
  Table,
  Tag,
  Image,
  Space,
  Popconfirm,
} from 'antd'
import { EditOutlined, DeleteOutlined } from '@ant-design/icons'
import { articleDel, articleList } from '@/store/actions/article'
import defaultImg from '@/assets/error.png'
import Channel from '@/components/Channel'

const STATUS = [
  { id: -1, title: '全部', color: 'magenta' },
  { id: 0, title: '草稿', color: 'red' },
  { id: 1, title: '待审核', color: 'volcano' },
  { id: 2, title: '审核通过', color: 'lime' },
  { id: 3, title: '审核失败', color: 'gold' },
]

export default function Article() {
  const dispatch = useDispatch()
  const { articles } = useSelector((state) => state.article)
  const params = useRef({})
  const onFinish = (values) => {
    if (values.status !== -1) {
      params.current.status = values.status
    } else {
      // 如果选择了草稿，name status 就是 0
      // 再切换到全部的时候，此时 values.status 等于 -1
      // 等于 -1 就进不到 if 条件了，导致 params.current.status 还是上一次选择的结果
      // 解决：status 等于 -1 的时候删掉此字段
      delete params.current.status
    }
    if (values.channel_id) {
      params.current.channel_id = values.channel_id
    }
    if (values.date) {
      params.current.begin_pubdate = values.date[0]
        .startOf('day')
        .format('YYYY-MM-DD HH:mm:ss')
      params.current.end_pubdate = values.date[1]
        .endOf('day')
        .format('YYYY-MM-DD HH:mm:ss')
    }
    // 每次筛选都从第一页开始
    params.current.page = 1
    // !根据处理完后的参数进行发请求
    dispatch(articleList(params.current))
  }
  const confirm = async (id) => {
    // 删除
    await dispatch(articleDel(id))
    // 重新获取列表
    await dispatch(articleList(params.current))
  }
  const columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      render: (cover) => {
        if (cover.type === 0) {
          return <Image width={200} src={defaultImg} />
        } else {
          return (
            <Image width={200} src={cover.images[0]} fallback={defaultImg} />
          )
        }
      },
    },
    {
      title: '标题',
      dataIndex: 'title',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (status) => {
        // 加了 dataIndex status，这里的参数就是每一行数据的 status
        // 不加 dataIndex status，这里的参数就是每一行的数据
        const obj = STATUS.find((item) => item.id === status)
        return <Tag color={obj.color}>{obj.title}</Tag>
      },
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
    },
    {
      title: '操作',
      dataIndex: 'id',
      render: (id) => {
        return (
          <Space size='middle'>
            <Button type='primary' shape='circle' icon={<EditOutlined />} />
            <Popconfirm
              placement='bottomRight'
              title='确定删除吗'
              onConfirm={() => confirm(id)}
            >
              <Button type='danger' shape='circle' icon={<DeleteOutlined />} />
            </Popconfirm>
          </Space>
        )
      },
    },
  ]
  useEffect(() => {
    dispatch(articleList())
  }, [dispatch])
  return (
    <div>
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to='/home'>首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>内容管理</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form
          autoComplete='off'
          onFinish={onFinish}
          initialValues={{
            status: -1,
          }}
        >
          {/* 状态 */}
          <Form.Item label='状态' name='status'>
            <Radio.Group>
              {STATUS.map((item) => (
                <Radio key={item.id} value={item.id}>
                  {item.title}
                </Radio>
              ))}
            </Radio.Group>
          </Form.Item>
          {/* 频道 */}
          <Form.Item label='频道' name='channel_id'>
            <Channel />
          </Form.Item>
          {/* 日期 */}
          <Form.Item label='日期' name='date'>
            <DatePicker.RangePicker />
          </Form.Item>
          {/* 提交按钮 */}
          <Form.Item>
            <Button type='primary' htmlType='submit'>
              筛选
            </Button>
          </Form.Item>
        </Form>
      </Card>
      <Card
        title={`根据筛选条件共查询到 ${articles.total_count} 条结果`}
        style={{ marginTop: 20 }}
      >
        <Table
          rowKey='id'
          dataSource={articles.results}
          columns={columns}
          pagination={{
            position: ['bottomCenter'],
            pageSize: articles.per_page,
            current: articles.page,
            total: articles.total_count,
            onChange: function (page, pageSize) {
              // page、per_page
              params.current.page = page
              params.current.per_page = pageSize
              dispatch(articleList(params.current))
            },
          }}
        />
      </Card>
    </div>
  )
}
